#include <iostream>
#include <string>
#include <cstdlib>
#include <vector>
#include <unistd.h>
#include <ctime>
#include <cstdint>

using namespace std;

enum
{
    UsageError = 1,
    CreatError
};

void Usage(const string &proc)
{
    cout << "usage:" << proc << "  sub_process_num" << endl;
}

class Channel
{
public:
    Channel(int wfd, int sub_process_id, string &name)
        : _wfd(wfd), _sub_process_id(sub_process_id), _name(name)
    {
    }

    void PrintDebug()
    {
        cout << "wfd:" << _wfd;
        cout << ",sub_process_id:" << _sub_process_id;
        cout << ",name:" << _name;
    }

    ~Channel()
    {
    }

private:
    int _wfd;
    int _sub_process_id;
    string _name;
};

class Processpool
{
public:
    Processpool(int sub_process_num)
    :_sub_process_num(sub_process_num)
    {}

    int CreatProcess()
    {
        for (int num = 0; num < _sub_process_num; num++)
        {
            int pipefd[2]{0};
            int n =pipe(pipefd);
            if(n<0)
            {
                return CreatError;
            }

            pid_t id = fork();
            if (id == 0)
            {
                // child  r
                close(pipefd[1]); // 关闭写段
                dup2(pipefd[0], 0);
                exit(0);
            }

            // father
            // 管理管道：先描述，再组织
            // vector<Channel> channels;
            string cname = "channel-" + to_string(num);
            close(pipefd[0]);
            channels.push_back(Channel(pipefd[1], num, cname));
            //Channel(pipefd[1], num, cname).PrintDebug();
        }
        return 1;
    }

    int NextChannel()
    {
        int next=0;
        int c=next;
        next++;
        next%=channels.size();
        return c;
    }

private:
    int _sub_process_num;
    vector<Channel> channels;
};

int main(int argc, char *argv[])
{
    if (argc != 2) // 没有输入正确的格式
    {
        Usage(argv[0]);
        return UsageError;
    }
    int sub_process_num = stoi(argv[1]);

    //创建进程
    Processpool *process_ptr=new Processpool(sub_process_num);
    process_ptr->CreatProcess();

    //
    process_ptr->NextChannel();
    

    return 0;
}